#include "Observer.h"
#include "Event.h"
#include "ABObserver.h"
#include "Application.h"

Observer* Singleton<Observer>::m_pInstance = NULL;

Observer::Observer()
{
}
Observer::~Observer()
{
}

void Observer::Update()
{
	if(Application::GetInstance().GetHGE()->Input_GetKeyState(HGEK_W))
	{
		Event myEvent;
		myEvent.id = Observer::GetInstance().Hash("W Key");
		NotifyObservers(&myEvent);
	}
}
const unsigned int Observer::Hash(const char* a_pKey)
{
	int sum = 0;
	int i = 0;
	while(a_pKey[i])
	{
		sum += a_pKey[i++];
	}
	return sum % 256;
}
bool Observer::AttachObserver(ABObserver *a_pObserver)
{
	//Ensure the observer isn't already in the list
	for(ObserverList::iterator iter = m_observers.begin(); iter != m_observers.end(); ++iter)
	{
		ABObserver* pElem = *iter;
		if(a_pObserver == pElem)
		{
			return false;
		}
	}
	m_observers.push_back(a_pObserver);

	return true;
}

bool Observer::DetachObserver(ABObserver *a_pObserver)
{
	for(ObserverList::iterator iter = m_observers.begin(); iter != m_observers.end(); ++iter)
	{
		ABObserver* pElem = *iter;
		if(a_pObserver == pElem)
		{
			m_observers.remove(pElem);
			return true;
		}
	}
	//Not Found
	return false;
}

void Observer::NotifyObservers(const Event* a_event)
{
	for(ObserverList::iterator iter = m_observers.begin(); iter != m_observers.end(); ++iter)
	{
		ABObserver* pElem = *iter;
		pElem->Notify(a_event);
	}
}